package org.jeecg.modules.demo.soOrderDetail.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.message.TemplateMessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.checkOrder.entity.checkOrder;
import org.jeecg.modules.demo.checkOrder.service.IcheckOrderService;
import org.jeecg.modules.demo.puInvoice.service.IPuInvoiceService;
import org.jeecg.modules.demo.soOrderDetail.entity.SoOrderDetail;
import org.jeecg.modules.demo.soOrderDetail.service.ISoOrderDetailService;
import org.jeecg.modules.demo.soQualityOrder.entity.SoQualityOrder;
import org.jeecg.modules.demo.soQualityOrder.service.ISoQualityOrderService;
import org.jeecg.modules.demo.soSaleOrder.entity.SoSaleOrder;
import org.jeecg.modules.demo.soSaleOrder.service.ISoSaleOrderService;
import org.jeecg.modules.demo.util.generateOddUtilXs;
import org.jeecg.modules.demo.warehouseorder.entity.WarehouseOrder;
import org.jeecg.modules.demo.warehouseorder.service.IWarehouseOrderService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 销售出库单
 * @Author: jeecg-boot
 * @Date: 2021-12-10
 * @Version: V1.0
 */
@Api(tags = "销售出库单")
@RestController
@RequestMapping("/sale/soOrderDetail")
@Slf4j
public class SoOrderDetailController extends JeecgController<SoOrderDetail, ISoOrderDetailService> {

    @Autowired
    private ISoOrderDetailService soOrderDetailService;

    @Autowired
    private ISoQualityOrderService soQualityOrderService;
    @Autowired
    private IWarehouseOrderService warehouseOrderService;
    @Autowired
    private ISoSaleOrderService soSaleOrderService;
    @Autowired
    private IcheckOrderService icheckOrderService;
    @Autowired
    private IPuInvoiceService puInvoiceService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;

    private static final String TITLE = "单据审核";
    private String getMessage(String name,String date) {
        String str ="由【"+name+"】于【"+date+"】发起的销售出库单需要您的审核，请及时查看！";
        return str;
    }

    private String getMsg(String name,String date) {
        String str ="由【"+name+"】于【"+date+"】发起的销售质检单需要您的审核，请及时查看！";
        return str;
    }

    /*---------------------------------主表处理-begin-------------------------------------*/

    /**
     * 分页列表查询
     *
     * @param soOrderDetail
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "销售出库单-分页列表查询")
    @ApiOperation(value = "销售出库单-分页列表查询", notes = "销售出库单-分页列表查询")
    @GetMapping(value = "/list")
    @PermissionData(pageComponent="yunxiao/inventory/SoOrderDetailList")
    public Result<?> queryPageList(SoOrderDetail soOrderDetail,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<SoOrderDetail> queryWrapper = QueryGenerator.initQueryWrapper(soOrderDetail, req.getParameterMap());
        queryWrapper.eq("CK_TYPE", 1);
        queryWrapper.eq("IS_DELETE", 0);
        Page<SoOrderDetail> page = new Page<SoOrderDetail>(pageNo, pageSize);
        IPage<SoOrderDetail> pageList = soOrderDetailService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    //其他出库单页面list
    @GetMapping(value = "/listOther")
    @PermissionData(pageComponent="yunxiao/inventory_other/SoOrderDetail_otherList")
    public Result<?> queryPageListOther(SoOrderDetail soOrderDetail,
                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                        HttpServletRequest req) {
        QueryWrapper<SoOrderDetail> queryWrapper = QueryGenerator.initQueryWrapper(soOrderDetail, req.getParameterMap());
        queryWrapper.ne("CK_TYPE", 1);
        queryWrapper.eq("IS_DELETE", 0);
        Page<SoOrderDetail> page = new Page<SoOrderDetail>(pageNo, pageSize);
        IPage<SoOrderDetail> pageList = soOrderDetailService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    //生成销售质检单
    @RequestMapping(value = "/addSoQuality", method = RequestMethod.POST)
    public Result<?> addSoQuality(@RequestBody JSONObject jsonObject,HttpServletRequest req) {
        if (soOrderDetailService.addSoQuality(jsonObject,req)) {
            return Result.OK("生成销售质检单成功！");
        }
        return Result.error("生成销售质检单失败!");

    }



    /**
     * 添加
     *
     * @param
     * @return
     */
//    @AutoLog(value = "销售出库单-添加")
//    @ApiOperation(value = "销售出库单-添加", notes = "销售出库单-添加")
//    @PostMapping(value = "/add")
//    public Result<?> add(@RequestBody JSONObject jsonObject,HttpServletRequest req) {
//        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        try {
//            SoSaleOrder soSaleOrder = JSON.parseObject(jsonObject.toJSONString(), SoSaleOrder.class);
//            SoOrderDetail soOrderDetail = JSON.parseObject(jsonObject.toJSONString(), SoOrderDetail.class);
//            WarehouseOrder wo = JSON.parseObject(jsonObject.toJSONString(), WarehouseOrder.class);
//            List<checkOrder> orders = icheckOrderService.getByWhNum(soOrderDetail.getWhNum());
//            if (!orders.isEmpty()) {
//                return Result.error(soOrderDetail.getWhNum() + "正在盘点，无法生成出库单，请选择未盘点仓库！");
//            }
//            WarehouseOrder warehouseOrder = warehouseOrderService.getByRkNo(wo.getWoNo());
//            SoOrderDetail sd = new SoOrderDetail();
//            sd.setSodQuantity(soSaleOrder.getSoKck());
//            sd.setXclNum(soOrderDetail.getXclNum());
//            sd.setShName(soOrderDetail.getShName());
//
//            String maxCode = "";
//            maxCode = soOrderDetailService.getMaxCode();
//
//            Map<String,String> codeMap = new HashMap<>();
//            if(maxCode == null){
//                codeMap.put("maxCode",null);
//            }else{
//                codeMap.put("maxCode",maxCode);
//            }
//            String tenantId = req.getHeader("tenant-id");
//            String tname = soSaleOrderService.getTname(tenantId);
//            String xsck = generateOddUtilXs.createCode(codeMap,tname+"CK_");
//
//            //已选入库单的现存量
//            BigDecimal qqs = wo.getStandingstock();
//            //出库单应出库量
//            BigDecimal sqs = sd.getSodQuantity();
//            if (sqs == null) {
//                sqs = BigDecimal.valueOf(0);
//            }
//            //如果入库单的现存量>=出库单应出库量，把出库单应出库量set到实际出库量，否则把已选入库单的现存量set到实际出库量
//            BigDecimal a = BigDecimal.valueOf(0);
//            if (qqs.compareTo(sqs) > -1) {
//                a = sqs;
//            } else {
//                a = qqs;
//            }
//            if (a.compareTo(sd.getXclNum()) == -1) {
//                return Result.error("实际出库数量不能大于" + a + "!");
//            }
//            BigDecimal d = qqs.subtract(sd.getXclNum());
//
//            warehouseOrder.setStandingstock(d);
//            warehouseOrderService.updateById(warehouseOrder);
//
//
//            //计算采购成本
//            List<PuInvoice> fp = new ArrayList<>();
//            List<PuInvoice> ykp = puInvoiceService.getYkpByPoOrder(warehouseOrder.getPoOrder());
//            String no = wo.getWoNo().substring(3,5);
//            List<PuInvoice> ps = null;
//            if (!no.equals("RK")){
//                ps = puInvoiceService.getBywoNo(warehouseOrder.getPuWoNo());
//            } else {
//                ps = puInvoiceService.getBywoNo(wo.getWoNo());
//            }
////            List<PuInvoice> ps = puInvoiceService.getBywoNo(wo.getWoNo());
//            if (ykp.size() > 0) {
//                for (PuInvoice s : ykp) {
//                    fp.add(s);
//                }
//            }
//            if (ps.size() > 0) {
//                for (PuInvoice s1 : ps) {
//                    fp.add(s1);
//                }
//            }
//            BigDecimal b = sd.getXclNum();
//            BigDecimal s = BigDecimal.valueOf(0.00);
//            if (fp == null) {
//                sd.setCbJine(warehouseOrder.getWsdj().multiply(sd.getXclNum()));
//            } else {
//
//                for (PuInvoice pi : fp) {
//                    if (b.compareTo(BigDecimal.valueOf(0.00)) == 1) {
//                        //如果销售用开票数量<=出库单实际出库量
//                        if (pi.getXsFpsl().compareTo(b) < 1) {
//                            s = s.add(pi.getWsdj().multiply(pi.getXsFpsl()));
//                            b = b.subtract(pi.getXsFpsl());
//                            pi.setXsFpsl(BigDecimal.valueOf(0.00));
//                            puInvoiceService.updateById(pi);
//                        } else {
//                            s = s.add(pi.getWsdj().multiply(b));
//                            pi.setXsFpsl(pi.getXsFpsl().subtract(b));
//                            b = b.subtract(b);
//                            puInvoiceService.updateById(pi);
//                        }
//                    }
//                }
//                sd.setCbJine(s.add(b.multiply(warehouseOrder.getWsdj())));
//            }
//
//
//            sd.setTradecode(soOrderDetail.getTradecode());
//            sd.setSoConNo(soOrderDetail.getSoConNo());
//            sd.setSoOrder(soOrderDetail.getSoOrder());
//            sd.setSodStatus(soOrderDetail.getSodStatus());
//            if (soOrderDetail.getSodDate() == null) {
//                sd.setSodDate(new Date());
//            } else {
//                sd.setSodDate(soOrderDetail.getSodDate());
//            }
//            sd.setSodNo(xsck);
//            sd.setPsTax(soSaleOrder.getPsTax());
//            sd.setSoStaff(soSaleOrder.getSoStaff());
//            sd.setJldw(soSaleOrder.getDanwei());
//            sd.setHsdj(soSaleOrder.getHsdj());
//            sd.setHsje(soSaleOrder.getHsdj().multiply(sd.getXclNum()));
//            sd.setWsdj(soSaleOrder.getWsdj());
//            sd.setWsje(soSaleOrder.getWsdj().multiply(sd.getXclNum()));
//            sd.setSl(BigDecimal.valueOf(soSaleOrder.getSl()));
//            sd.setIsQuality(0);
//            sd.setIsDelete(0);
//            sd.setSodStatus(0);
//            sd.setSoCustom(soOrderDetail.getSoCustom());
//            sd.setDept(soSaleOrder.getDept());
//            //            sd.setCbJine(warehouseOrder.getFtwsdj().multiply(sd.getXclNum()));
//            sd.setTarget(soSaleOrder.getTarget());
//            sd.setWhNum(soOrderDetail.getWhNum());
//            sd.setPuWhNum(soOrderDetail.getPuWhNum());
//            sd.setPrdNo(soSaleOrder.getPrdNo());
//            sd.setProject(soSaleOrder.getProject());
//            sd.setCkType(soOrderDetail.getCkType());
//            sd.setPrdLot(wo.getPrdBn());
//            sd.setPrice(soOrderDetail.getPrice());
//            sd.setRkNo(wo.getWoNo());
//            sd.setYwType(soSaleOrder.getYwType());
//            sd.setCreateTime(new Date());
//            sd.setTzJine(BigDecimal.valueOf(0.00));
//            sd.setTzhJine(sd.getCbJine());
//            sd.setBjXcl(sd.getXclNum());
//            sd.setBjRkno(wo.getWoNo());
//            soOrderDetailService.save(sd);
//
//            SoSaleOrder sso = soSaleOrderService.getBysoNo(soSaleOrder.getSoOrder());
//            if (sso.getSoLjck() == null) {
//                sso.setSoLjck(BigDecimal.valueOf(0));
//            }
//            sso.setSoLjck(sso.getSoLjck().add(sd.getXclNum()));
//            sso.setSoKck(sso.getSoTotail().subtract(sso.getSoLjck()));
//            //累计出库量>=订单总量时
//            if (sso.getSoLjck().compareTo(sso.getSoTotail()) > -1) {
//                sso.setIsQuality(1);
//            }
//            if(sso.getSoKck().compareTo(BigDecimal.valueOf(0)) == 0){
//                sso.setIsQuality(1);
//            }
//            soSaleOrderService.updateById(sso);
//
//
//
//            LoginUser user = sysBaseAPI.getUserById(sd.getSoStaff());
//            TemplateMessageDTO templateMessageDTO = new TemplateMessageDTO();
//            templateMessageDTO.setFromUser("管理员");
//            templateMessageDTO.setToUser(sd.getShName()+",");
//            templateMessageDTO.setTitle(TITLE);
//            templateMessageDTO.setTemplateCode("order");
//            Map<String, String> templateParam = new HashMap<>();
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            String date= simpleDateFormat.format(new Date());
//            templateParam.put("ts_date",date);
//            templateParam.put("ts_content",getMessage(user.getRealname(),date));
//            templateParam.put("checkOrder",sd.getSodNo());
//            templateParam.put("cd_url","/yunxiao/inventory/SoOrderDetailList");
//            templateMessageDTO.setTemplateParam(templateParam);
//            sysBaseAPI.sendTemplateAnnouncement(templateMessageDTO);
//
//            return Result.OK("生成出库单成功!");
//        } catch (Exception e) {
//            log.error(e.getMessage(), e);
//            return Result.error("操作失败");
//        }
//    }


    //生成销售出库单
    @RequestMapping(value = "/addSoOrderDetail", method = RequestMethod.POST)
    public Result<?> addSoOrderDetail(@RequestBody JSONObject jsonObject,HttpServletRequest req) {
        SoSaleOrder soSaleOrder = JSON.parseObject(jsonObject.toJSONString(), SoSaleOrder.class);
        SoOrderDetail soOrderDetail = JSON.parseObject(jsonObject.toJSONString(), SoOrderDetail.class);
        WarehouseOrder wo = JSON.parseObject(jsonObject.toJSONString(), WarehouseOrder.class);
        List<checkOrder> orders = icheckOrderService.getByWhNum(soOrderDetail.getWhNum());
        if (!orders.isEmpty()) {
            return Result.error(soOrderDetail.getWhNum() + "正在盘点，无法生成出库单，请选择未盘点仓库！");
        }
        if (soOrderDetailService.addSoOrderDetail(soOrderDetail,soSaleOrder,req)) {
            return Result.OK("生成出库单成功！");
        }
        return Result.error("生成出库单失败!");
    }

    /**
     * 编辑
     *
     * @param soOrderDetail
     * @return
     */
    @AutoLog(value = "销售出库单-编辑")
    @ApiOperation(value = "销售出库单-编辑", notes = "销售出库单-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody SoOrderDetail soOrderDetail) {

//        if (soOrderDetailService.editRkandOrder(soOrderDetail)) {
            soOrderDetail.setBjRkno(soOrderDetail.getRkNo());
            soOrderDetail.setBjXcl(soOrderDetail.getXclNum());
            soOrderDetailService.updateById(soOrderDetail);
            return Result.OK("编辑成功！");

    }

    //生成出库单页面根据煤种和仓库查询
    @GetMapping(value = "/getByprdAndWh")
    public Result<?> getByprdAndWh(WarehouseOrder warehouseOrder,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<WarehouseOrder> page = new Page<WarehouseOrder>(pageNo, pageSize);
        List<WarehouseOrder> ss = soOrderDetailService.getByprdAndWh(warehouseOrder);
        return Result.OK(ss);
    }

    @GetMapping(value = "/getBysoNo")
    public Result<?> getBysoNo(@RequestParam(name = "soNo", required = true) String soNo) {
        List<SoOrderDetail> ss = soOrderDetailService.getBysoNo(soNo);
        return Result.OK(ss);
    }

    @GetMapping(value = "/getRkdByrkNo")
    public Result<?> getRkdByrkNo(@RequestParam(name = "rkNo", required = true) String rkNo) {
        WarehouseOrder warehouseOrder = warehouseOrderService.getByRkNo(rkNo);
        return Result.OK(warehouseOrder);
    }
    //审核弃审
    @PutMapping(value = "/editShenhe")
    public Result<?> editShenhe(@RequestBody SoOrderDetail soOrderDetail) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //		 List<checkOrder> orders = icheckOrderService.getByWhNum(soOrderDetail.getWhNum());
        //		 if(!orders.isEmpty()){
        //			 return Result.error(300,"仓库正在盘点，无法审核！");
        //		 }
        if (!soOrderDetail.getShName().equals(sysUser.getId())){
            return Result.error(300,"您不是当前单据的指定审核人！");
        }
        if (soOrderDetail.getSodStatus() == 1) {
//                    soOrderDetail.setShName(sysUser.getRealname());
            soOrderDetail.setShTime(new Date());
        } else {
//                    soOrderDetail.setShName("");
            soOrderDetail.setShTime(null);
        }
        //		 if (soOrderDetail.getIsShjl() == "" || soOrderDetail.getIsShjl() == null){
        //			 WarehouseOrder warehouseOrder = warehouseOrderService.getByRkNo(soOrderDetail.getRkNo());
        //			 warehouseOrder.setStandingstock(warehouseOrder.getStandingstock().subtract(soOrderDetail.getXclNum()));
        //			 warehouseOrderService.updateById(warehouseOrder);
        //			 soOrderDetail.setIsShjl("1");
        //		 }
        soOrderDetailService.updateById(soOrderDetail);
        return Result.OK("编辑成功!");
    }

    //假删除并加回入库单现存量,并改变销售订单表累计出库量和可出库量
    @PutMapping(value = "/editRk")
    public Result<?> editRk(@RequestBody SoOrderDetail soOrderDetail) {
        ////		 if ("1".equals(soOrderDetail.getIsShjl())) {
        //        WarehouseOrder ws = warehouseOrderService.getByRkNo(soOrderDetail.getRkNo());
        //        ws.setStandingstock(ws.getStandingstock().add(soOrderDetail.getXclNum()));
        //        warehouseOrderService.updateById(ws);
        ////		 }
        //        SoSaleOrder sso = soSaleOrderService.getBysoNo(soOrderDetail.getSoOrder());
        //        sso.setSoLjck(sso.getSoLjck().subtract(soOrderDetail.getXclNum()));
        //        sso.setSoKck(sso.getSoTotail().subtract(sso.getSoLjck()));
        //        sso.setIsQuality(0);
        //        soSaleOrderService.updateById(sso);
        if (soOrderDetailService.editRk(soOrderDetail)) {
            soOrderDetailService.removeById(soOrderDetail);
            return Result.OK("删除成功！");
        }
        return Result.error("删除失败!");
    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "销售出库单-通过id删除")
    @ApiOperation(value = "销售出库单-通过id删除", notes = "销售出库单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        soOrderDetailService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "销售出库单-批量删除")
    @ApiOperation(value = "销售出库单-批量删除", notes = "销售出库单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.soOrderDetailService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SoOrderDetail soOrderDetail) {
        return super.exportXls(request, soOrderDetail, SoOrderDetail.class, "销售出库单");
    }

    /**
     * 导入
     *
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SoOrderDetail.class);
    }
    /*---------------------------------主表处理-end-------------------------------------*/


    /*--------------------------------子表处理-销售质检单-begin----------------------------------------------*/

    /**
     * 通过主表ID查询
     *
     * @return
     */
    @AutoLog(value = "销售质检单-通过主表ID查询")
    @ApiOperation(value = "销售质检单-通过主表ID查询", notes = "销售质检单-通过主表ID查询")
    @GetMapping(value = "/listSoQualityOrderByMainId")
    public Result<?> listSoQualityOrderByMainId(SoQualityOrder soQualityOrder,
                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                HttpServletRequest req) {
        QueryWrapper<SoQualityOrder> queryWrapper = QueryGenerator.initQueryWrapper(soQualityOrder, req.getParameterMap());
        Page<SoQualityOrder> page = new Page<SoQualityOrder>(pageNo, pageSize);
        IPage<SoQualityOrder> pageList = soQualityOrderService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param
     * @return
     */
    @AutoLog(value = "销售质检单-添加")
    @ApiOperation(value = "销售质检单-添加", notes = "销售质检单-添加")
    @PostMapping(value = "/addSoQualityOrder")
    public Result<?> addSoQualityOrder(@RequestBody JSONObject jsonObject,HttpServletRequest req) {
        try {
            SoOrderDetail soOrderDetail = JSON.parseObject(jsonObject.toJSONString(), SoOrderDetail.class);
            SoQualityOrder sqo = JSON.parseObject(jsonObject.toJSONString(), SoQualityOrder.class);
            List<SoQualityOrder> list = this.soQualityOrderService.list();
            Collections.sort(list);

            String maxCode = "";
            if (list.size() > 0) {
                maxCode = list.get(0).getQoNum();
            }
            Map<String,String> codeMap = new HashMap<>();
            if(maxCode == null){
                codeMap.put("maxCode",null);
            }else{
                codeMap.put("maxCode",maxCode);
            }
            String tenantId = req.getHeader("tenant-id");
            String tname = soSaleOrderService.getTname(tenantId);
            String xszj = generateOddUtilXs.createCode(codeMap,tname+"ZJ_");

            sqo.setId("");
            sqo.setPuConNo(soOrderDetail.getSoConNo());
            sqo.setSoOrder(soOrderDetail.getSoOrder());
            if (sqo.getQoDate() == null) {
                sqo.setQoDate(new Date());
            }

            sqo.setQoNum(xszj);
            sqo.setSosStaff(soOrderDetail.getSoStaff());
            sqo.setSodNo(soOrderDetail.getSodNo());
            sqo.setQoType(1);
            sqo.setChuku(0);
            sqo.setSl(soOrderDetail.getSl());
            sqo.setCkNum(soOrderDetail.getXclNum());
            sqo.setSyNum(sqo.getQoQuantity());
            //			sqo.setHsdj();
            //			sqo.setHsje();
            //			sqo.setWsje();
            //			sqo.setWsdj();
            //			sqo.setJldw();
            //			 sqo.setQoQuantity(0);
            //			 sqo.setQoCal(0);
            //			 sqo.setQoPic(Double.valueOf(0));
            //			 sqo.setQoTotal(Double.valueOf(0));
            //			 sqo.setQoTaxrate(Double.valueOf(0));
            //			 sqo.setQoTax(Double.valueOf(0));
            //			 sqo.setQoNotax(Double.valueOf(0));
            sqo.setSoStatus(0);
            sqo.setIsDelete(0);
            sqo.setCreateTime(new Date());
            sqo.setTradecode(sqo.getTradecode());
            soQualityOrderService.save(sqo);
            //			soOrderDetail.setIsQuality(1);
            SoOrderDetail s = soOrderDetailService.getBySodNo(soOrderDetail.getSodNo(), soOrderDetail.getSoOrder());
            s.setIsQuality(1);
            soOrderDetailService.updateById(s);
            //			SoSaleOrder sso = soSaleOrderService.getBysoNo(sqo.getSoOrder());
            //			BigDecimal a = sqo.getCkNum().subtract(sqo.getQoQuantity());
            //			sso.setSoLjck(sso.getSoLjck().subtract(a));
            //			sso.setSoKck(sso.getSoTotail().subtract(sso.getSoLjck()));
            //			if (sso.getSoLjck().compareTo(sso.getSoTotail()) > -1){
            //				sso.setIsQuality(1);
            //			} else {
            //				sso.setIsQuality(0);
            //			}
            //			soSaleOrderService.updateById(sso);

            LoginUser user = sysBaseAPI.getUserById(sqo.getSosStaff());
            TemplateMessageDTO templateMessageDTO = new TemplateMessageDTO();
            templateMessageDTO.setFromUser("管理员");
            templateMessageDTO.setToUser(sqo.getShName()+",");
            templateMessageDTO.setTitle(TITLE);
            templateMessageDTO.setTemplateCode("order");
            Map<String, String> templateParam = new HashMap<>();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date= simpleDateFormat.format(new Date());
            templateParam.put("ts_date",date);
            templateParam.put("ts_content",getMessage(user.getRealname(),date));
            templateParam.put("checkOrder",sqo.getQoNum());
            templateParam.put("cd_url","/yunxiao/quality/SoSaleOrderList2");
            templateMessageDTO.setTemplateParam(templateParam);
            sysBaseAPI.sendTemplateAnnouncement(templateMessageDTO);


            return Result.OK("生成质检单成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("操作失败");
        }
    }

    /**
     * 编辑
     *
     * @param soQualityOrder
     * @return
     */
    @AutoLog(value = "销售质检单-编辑")
    @ApiOperation(value = "销售质检单-编辑", notes = "销售质检单-编辑")
    @PutMapping(value = "/editSoQualityOrder")
    public Result<?> editSoQualityOrder(@RequestBody SoQualityOrder soQualityOrder) {
        soQualityOrder.setSyNum(soQualityOrder.getQoQuantity());
        soQualityOrderService.updateById(soQualityOrder);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "销售质检单-通过id删除")
    @ApiOperation(value = "销售质检单-通过id删除", notes = "销售质检单-通过id删除")
    @DeleteMapping(value = "/deleteSoQualityOrder")
    public Result<?> deleteSoQualityOrder(@RequestParam(name = "id", required = true) String id) {
        soQualityOrderService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "销售质检单-批量删除")
    @ApiOperation(value = "销售质检单-批量删除", notes = "销售质检单-批量删除")
    @DeleteMapping(value = "/deleteBatchSoQualityOrder")
    public Result<?> deleteBatchSoQualityOrder(@RequestParam(name = "ids", required = true) String ids) {
        this.soQualityOrderService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/exportSoQualityOrder")
    public ModelAndView exportSoQualityOrder(HttpServletRequest request, SoQualityOrder soQualityOrder) {
        // Step.1 组装查询条件
        QueryWrapper<SoQualityOrder> queryWrapper = QueryGenerator.initQueryWrapper(soQualityOrder, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<SoQualityOrder> pageList = soQualityOrderService.list(queryWrapper);
        List<SoQualityOrder> exportList = null;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "销售质检单"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, SoQualityOrder.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("销售质检单报表", "导出人:" + sysUser.getRealname(), "销售质检单"));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 导入
     *
     * @return
     */
    @RequestMapping(value = "/importSoQualityOrder/{mainId}")
    public Result<?> importSoQualityOrder(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<SoQualityOrder> list = ExcelImportUtil.importExcel(file.getInputStream(), SoQualityOrder.class, params);
                for (SoQualityOrder temp : list) {
                    temp.setSodNo(mainId);
                }
                long start = System.currentTimeMillis();
                soQualityOrderService.saveBatch(list);
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                return Result.OK("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-销售质检单-end----------------------------------------------*/


}
